package gruppoSoluzione.mainService.services;

import gruppoSoluzione.mainService.HTTPService;
import gruppoSoluzione.mainService.ServiceParams;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Un generico File Server, gestisce file html, file css e file js
 * 
 * @author Alessandro Martinelli
 */
public class HttpFileServer implements HTTPService{

	@Override
	public ArrayList<String> getServiceResult(ServiceParams params) {
	
		String filename=params.getValue("file");

		if(filename==null){
			filename="error.html";
		}
		
		MimeHTTP mime=MimeHTTP.getMimeByFilename(filename);
		
		File file=new File("web/"+filename);
		
		if(!file.exists() || file.isDirectory()){
			file=new File("web/error.html");
		}
		
		HttpMessageWriter writer=new HttpMessageWriter(mime);
		ArrayList<String> risposta=writer.createHttpMessageHeader();
		
		try {
			BufferedReader reader=new BufferedReader(new FileReader(file));
			String line=reader.readLine();
			while(line!=null){
				risposta.add(line);
				line=reader.readLine();
			}
			reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return risposta;
	}
}
